package com.lmu.travel.controller;

import com.lmu.travel.entity.Result;
import com.lmu.travel.util.Create;
import com.lmu.travel.util.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liuxuhuang
 * @className: MailController
 * @description: 邮件发送接口
 * @email liuxuhuang3970@qq.com
 * @date 2021/6/27 20:20
 * @version：1.0
 */
@RestController
@RequestMapping(value = "email")
@Api(value = "邮件发送接口")
public class MailController {
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    RedisUtil redisUtil;

    @RequestMapping(value = "sendMail/{receiver}", method = {RequestMethod.GET, RequestMethod.POST})
    @ApiImplicitParam(name = "receiver", required = true, format = "email")
    @ApiOperation("注册时发送邮件验证")
    public Result sendMail(@PathVariable("receiver") String receiver) {
        if (!redisUtil.exists(receiver)) {
            Create create = new Create();
            String verification = create.getRandomString(6);
            redisUtil.set(receiver, verification);
            send(receiver, verification);
            return new Result(200, true, null, "发送邮件成功");
        } else {
            if (redisUtil.delete(receiver)) {
                Create create = new Create();
                String verification = create.getRandomString(6);
                redisUtil.set(receiver, verification);
                send(receiver, verification);
                return new Result(200, true, null, "发送邮件成功");
            } else {
                return new Result(201, false, null, "验证码已发送，请5分钟后重试");
            }

        }
    }

    /**
     * 发送邮件
     *
     * @param receiver
     */
    public void send(String receiver, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(receiver);
        message.setFrom("liuxuhuang3970@qq.com");
        message.setSubject("旅游网邮件提醒");
        message.setText("[旅游网]注册验证码：" + String.valueOf(content));
        try {
            mailSender.send(message);
        } catch (MailException e) {
            e.printStackTrace();
        }
    }
}
